const express = require('express');
const formidable = require('formidable');
const UserModel = require('../db/models/UserModel')
const {
    RES_CODE
} = require('../utils/constants');
const path = require('path');
const md5 = require('md5');
const router = express.Router();

//注册分页列表路由
router.get('/user/:page/:limit', async (req, res) => {
    //获取参数
    const {
        page,
        limit
    } = req.params;
    //计算skip
    const skip = (page - 1) * limit;
    //得到当前页的用户列表
    const users = await UserModel.find({username:{$ne:'admin'}}).skip(skip).limit(limit)
    //得到总数量
    const total = await UserModel.count({username:{$ne:'admin'}});

    return res.json({
        code: RES_CODE.SUCCESS,
        data: {
            users,
            total
        },
        message: '查询用户列表成功'
    })

})
//获取用户信息
router.get('/user', async (req, res) => {
    //得到参数
    const {
        id
    } = req.query
    console.log(id);
    //查询对应的user
    const user = await UserModel.findById(id);
    if (user) {
        res.send({
            code: RES_CODE.SUCCESS,
            data: user,
            message: '获取用户信息成功'
        })
    } else {
        //返回响应
        res.json({
            code: RES_CODE.DATA_ERROR,
            message: '找不到当前用户'
        })
    }
})

//删除指定用户
router.delete('/user/:id', async (req, res) => {
    const {
        id
    } = req.params
    await UserModel.deleteOne({
        _id: id
    })
    res.send({
        code: RES_CODE.SUCCESS,
        message: '删除用户成功'
    })
})

// 添加用户
router.post('/user', (req, res) => {
    //读取参数数据
    console.log(req.body);
    //创建解析请求的form对象
    const form = formidable({
        uploadDir: path.resolve(__dirname, '../public/upload'), // 上传保存的文件夹的绝对路径
        keepExtensions: true, // 保留扩展名 默认是false
    })
    //解析请求 =>自动保存文件
    form.parse(req, async (error, fields, files) => {
        if (error) {
            return res.json({
                code: RES_CODE.DATA_ERROR,
                message: error.message
            })
        }
        // console.log(fields['username'])
        // console.log(fields['pwd'])
        // console.log(files['profileFile'])
        const {
            username,
            pwd
        } = fields;
        // 查询判断是否有此用户名的用户, 如果有, 返回错误响应
        let user = await UserModel.findOne({
            username
        });
        if (user) {
            return res.json({
                code: RES_CODE.DATA_ERROR,
                message: '此用户已存在'
            })
        }
        // 准备去添加一个新用户
        // "profile": "/upload/xxx.jpg",
        // 得到文件对象
        const file = files['profileFile']
        //得到生成的文件名
        const filename = file.newFilename
        //文件访问路径
        const profile = '/upload/' + filename
        //插入到数据库
        user = await UserModel.create({ username, pwd:md5(pwd), profile })
        //返回成功响应
        res.json({
            code: RES_CODE.SUCCESS,
            data: user,
            message:'添加用户成功'
        })
    })
})

//更新用户
router.put('/user', (req, res) => {
    //解析请求体
    form.parse(req, async (error, fields, files) => {
        if (error) {
            return res.json({
                code: RES_CODE.DATA_ERROR,
                message:error.message
            })
        }
        //读取参数数据
        const { _id, username } = fields
        const filename = files['profileFile'].newFilename
        const profile = '/upload/' + filename
        //更新对应的User
        await UserModel.updateOne({ _id }, { username, profile })
        //返回成功响应
        res.json({
            code: RES_CODE.SUCCESS,
            message:'成功用户成功!'
        })
    })
})
module.exports = router;